package com.yc.qunxing.web;

import com.yc.qunxing.common.QrCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@Slf4j
public class QrCodeController {

    @GetMapping("/qrcode")
    public void generateQrCode(HttpSession session, HttpServletResponse response) {
        response.setContentType("image/png;charset=UTF-8");

        // 获取二维码内容
        String content = (String) session.getAttribute("qccode");
        log.info("二维码内容: {}", content);

        if (content == null) {
            content = "fail";
        }

        OutputStream output = null;
        try {
            output = response.getOutputStream();
            byte[] qrCodeImage = QrCodeUtils.buildQrCodeImage(content);
            output.write(qrCodeImage);
        } catch (IOException e) {
            throw new RuntimeException("生成二维码图片时出现异常", e);
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭输出流时出现异常", e);
                }
            }
        }
    }
}
